import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface FormField {
  id: string | null
  name: string
  nickName: string
  type: string
  icon: string
  parentId: string | null
  slot: string | null
  isShow: boolean
  attrs: Record<string, any>
  style: {
    width: number
    height: number
    x: number
    y: number
    [key: string]: any
  },
  validation?: [] | false
}

export interface FormStructure {
  id: string
  title: string
  description?: string
  mode: 'layout' | 'free'
  fields: FormField[]
  style?: {
    backgroundColor?: string
    borderRadius?: string
    boxShadow?: string
  }
}

export const useFormDesignerStore = defineStore('formDesigner', () => {
  // 当前表单结构
  const currentForm = ref<FormStructure>({
    id: 'default-form',
    title: '新建表单',
    description: '',
    fields: [],
    mode: 'layout'
  })

  // 选中的字段
  const selectedField = ref<FormField | null>(null)

  // 设计历史（用于撤销/重做）
  const history = ref<FormStructure[]>([])
  const historyIndex = ref(-1)

  // 计算属性
  const fieldCount = computed(() => currentForm.value.fields.length)
  const hasFields = computed(() => fieldCount.value > 0)

  // 添加字段
  const addField = (field: Omit<FormField, 'id'>) => {
    const newField: FormField = {
      ...field,
      id: `field_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    }

    currentForm.value.fields.push(newField)
    saveToHistory()
    return newField
  }

  // 删除字段
  const removeField = (fieldId: string) => {
    const index = currentForm.value.fields.findIndex(field => field.id === fieldId)
    if (index > -1) {
      currentForm.value.fields.splice(index, 1)
      if (selectedField.value?.id === fieldId) {
        selectedField.value = null
      }
      saveToHistory()
    }
  }

  // 更新字段
  const updateField = (fieldId: string, updates: Partial<FormField>) => {
    const field = currentForm.value.fields.find(f => f.id === fieldId)
    if (field) {
      Object.assign(field, updates)
      saveToHistory()
    }
  }

  // 选择字段
  const selectField = (field: FormField | null) => {
    selectedField.value = field
  }

  // 应用表单结构
  const applyFormStructure = (structure: Partial<FormStructure>) => {
    if (structure.title) {
      currentForm.value.title = structure.title
    }

    if (structure.fields) {
      // 清空现有字段
      currentForm.value.fields = []

      // 添加新字段
      structure.fields.forEach(fieldData => {
        addField(fieldData)
      })
    }

    if (structure.layout) {
      currentForm.value.layout = { ...currentForm.value.layout, ...structure.layout }
    }

    if (structure.style) {
      currentForm.value.style = { ...currentForm.value.style, ...structure.style }
    }

    saveToHistory()
  }

  // 保存到历史记录
  const saveToHistory = () => {
    const formCopy = JSON.parse(JSON.stringify(currentForm.value))

    // 删除当前索引之后的历史记录
    history.value = history.value.slice(0, historyIndex.value + 1)

    // 添加新的历史记录
    history.value.push(formCopy)
    historyIndex.value = history.value.length - 1

    // 限制历史记录数量
    if (history.value.length > 50) {
      history.value.shift()
      historyIndex.value--
    }
  }

  // 撤销
  const undo = () => {
    if (historyIndex.value > 0) {
      historyIndex.value--
      currentForm.value = JSON.parse(JSON.stringify(history.value[historyIndex.value]))
    }
  }

  // 重做
  const redo = () => {
    if (historyIndex.value < history.value.length - 1) {
      historyIndex.value++
      currentForm.value = JSON.parse(JSON.stringify(history.value[historyIndex.value]))
    }
  }

  // 清空表单
  const clearForm = () => {
    currentForm.value = {
      id: 'default-form',
      title: '新建表单',
      fields: [],
      layout: {
        columns: 1,
        gap: 16,
        padding: 20
      }
    }
    selectedField.value = null
    saveToHistory()
  }

  // 导出表单配置
  const exportForm = () => {
    return JSON.stringify(currentForm.value, null, 2)
  }

  // 导入表单配置
  const importForm = (formJson: string) => {
    try {
      const formData = JSON.parse(formJson)
      currentForm.value = formData
      selectedField.value = null
      saveToHistory()
      return true
    } catch (error) {
      console.error('导入表单配置失败:', error)
      return false
    }
  }

  // 生成表单代码
  const generateFormCode = () => {
    const form = currentForm.value

    const vueTemplate = `
<template>
  <div class="form-container">
    <h2>${form.title}</h2>
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
      ${form.fields.map(field => generateFieldTemplate(field)).join('\n      ')}
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const formRef = ref()
const formData = reactive({
  ${form.fields.map(field => `${field.id}: ''`).join(',\n  ')}
})

const rules = {
  ${form.fields.filter(field => field.required).map(field =>
      `${field.id}: [
    { required: true, message: '请输入${field.label}', trigger: 'blur' }
  ]`
    ).join(',\n  ')}
}

const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      ElMessage.success('提交成功!')
      console.log('表单数据:', formData)
    } else {
      ElMessage.error('请检查表单输入')
    }
  })
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<style scoped>
.form-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}
</style>
    `

    return vueTemplate
  }

  // 生成字段模板
  const generateFieldTemplate = (field: FormField): string => {
    const label = field.label
    const prop = field.id
    const required = field.required ? ' *' : ''
    const placeholder = field.placeholder ? ` placeholder="${field.placeholder}"` : ''

    switch (field.type) {
      case 'input':
        return `<el-form-item label="${label}${required}" prop="${prop}">
        <el-input v-model="formData.${prop}"${placeholder}></el-input>
      </el-form-item>`

      case 'textarea':
        return `<el-form-item label="${label}${required}" prop="${prop}">
        <el-input v-model="formData.${prop}" type="textarea"${placeholder}></el-input>
      </el-form-item>`

      case 'select':
        const options = field.options?.map(opt =>
          `<el-option label="${opt.label}" value="${opt.value}"></el-option>`
        ).join('\n        ') || ''
        return `<el-form-item label="${label}${required}" prop="${prop}">
        <el-select v-model="formData.${prop}"${placeholder}>
          ${options}
        </el-select>
      </el-form-item>`

      case 'radio':
        const radioOptions = field.options?.map(opt =>
          `<el-radio label="${opt.value}">${opt.label}</el-radio>`
        ).join('\n        ') || ''
        return `<el-form-item label="${label}${required}" prop="${prop}">
        <el-radio-group v-model="formData.${prop}">
          ${radioOptions}
        </el-radio-group>
      </el-form-item>`

      case 'checkbox':
        return `<el-form-item label="${label}${required}" prop="${prop}">
        <el-checkbox v-model="formData.${prop}">${label}</el-checkbox>
      </el-form-item>`

      case 'date':
        return `<el-form-item label="${label}${required}" prop="${prop}">
        <el-date-picker v-model="formData.${prop}" type="date"${placeholder}></el-date-picker>
      </el-form-item>`

      default:
        return `<el-form-item label="${label}${required}" prop="${prop}">
        <el-input v-model="formData.${prop}"${placeholder}></el-input>
      </el-form-item>`
    }
  }

  return {
    // 状态
    currentForm,
    selectedField,
    history,
    historyIndex,

    // 计算属性
    fieldCount,
    hasFields,

    // 方法
    addField,
    removeField,
    updateField,
    selectField,
    applyFormStructure,
    undo,
    redo,
    clearForm,
    exportForm,
    importForm,
    generateFormCode
  }
})
